<?php
require_once 'util/class.dbservice.php';

class CommentDao {

	public function addComment($id, $userId, $noteId, $comment, $timestamp, $src=0) {
		try {
			$collection = $this->getCollection($noteId);
			if(!$collection)
				return;

			$collection->insert(array('_id'=>$id, 'uid'=>$userId, 'nid'=>$noteId,
					'note'=>$comment, 'ts'=>$timestamp, 'src'=>$src));
		} catch(Exception $e) {
			syslog(LOG_ERR, "CommentDao.addComment error, reason=".$e);
		}
	}
	
	public function getComment($userId, $noteId, $timestamp) {
		try {
			$collection = $this->getCollection($noteId);
			if(!$collection)
				return;
		
			return $collection->findOne(array('uid'=>$userId, 'nid'=>$noteId,'ts'=>$timestamp));
		} catch(Exception $e) {
			syslog(LOG_ERR, "CommentDao.getComment error, reason=".$e);
			return null;
		}
	}
	
	public function getCommentList($noteId, $pageSize, $sinceCommentId) {
		try {
			$collection = $this->getCollection($noteId);
			if(!$collection)
				return;
			
			if($sinceCommentId==0) 
				$cursor=$collection->find(array('nid'=>$noteId, '_id'=>array('$gt'=>$sinceCommentId)))
					->sort(array('ts'=>-1))->limit($pageSize);
			else
				$cursor=$collection->find(array('nid'=>$noteId, '_id'=>array('$lt'=>$sinceCommentId)))
					->sort(array('ts'=>-1))->limit($pageSize);
	 		
	 		$result=array();
	 		foreach ($cursor as $doc) {
	 			$result[]=$doc;
	 		}
			return $result;
		} catch(Exception $e) {
			syslog(LOG_ERR, "CommentDao.getCommentList error, reason=".$e);
			return null;
		}
	}

	private function getCollection($noteId) {
		$db=DBService::getDbById('note', $noteId);
		$collectionName = DBService::getCollectionNameById('comments', $noteId);
		return $db->$collectionName;
	}
}